package com.zhuang.yygh.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Jwt工具类
 **/
public class JwtHelper {
    //token过期时间，毫秒值
    private static long tokenExpiration = 24*60*60*1000;
    //token签名密钥
    private static String tokenSignKey = "123456";

    //根据参数(用户id、用户名)生成token字符串
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                //设置分类名称
                .setSubject("YYGH-USER")
                //设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //设置主体信息
                .claim("userId", userId)
                .claim("userName", userName)
                //设置签名哈希，签名主要是对JWT生成字符串的时候，进行加密
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //根据token字符串得到用户id
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }

    //根据token字符串得到用户名
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }


    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "zhuang");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));
    }
}

